package com.cens.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cens.common.utils.HttpUtils;
import com.cens.mall.member.dao.MemberLevelDao;
import com.cens.mall.member.entity.MemberLevelEntity;
import com.cens.mall.member.exception.PhoneExistException;
import com.cens.mall.member.exception.UserNameExistException;
import com.cens.mall.member.vo.MemberLoginVo;
import com.cens.mall.member.vo.MemberRegistVo;
import com.cens.mall.member.vo.SocialWeiboUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.member.dao.MemberDao;
import com.cens.mall.member.entity.MemberEntity;
import com.cens.mall.member.service.MemberService;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //检查用户名/手机号的唯一性
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUserName());
        //加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(passwordEncoder.encode(vo.getPassword()));
        //查询并设置默认等级
        MemberLevelEntity level = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(level.getId());
        baseMapper.insert(memberEntity);
    }


    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        if (baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, userName)) > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        if (baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone)) > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String account = vo.getAccount();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        MemberEntity entity = baseMapper.selectOne(
                new LambdaQueryWrapper<MemberEntity>()
                        .eq(MemberEntity::getMobile, account)
                        .or()
                        .eq(MemberEntity::getUsername, account)
        );
        if(entity != null && passwordEncoder.matches(vo.getPassword(),entity.getPassword())){
            return entity;
        }else{
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialWeiboUser socialWeiboUser) throws Exception {
        String uid = socialWeiboUser.getUid();
        //判断当前用户是否已经登录过
        MemberEntity entity = this.baseMapper.selectOne(
                new LambdaQueryWrapper<MemberEntity>()
                        .eq(MemberEntity::getSocialUid, uid)
        );
        if(entity != null){
            entity.setAccessToken(socialWeiboUser.getAccess_token());
            entity.setExpiresIn(socialWeiboUser.getExpires_in());
            this.baseMapper.updateById(entity);
        }else{
            //注册
            entity = new MemberEntity();
            entity.setSocialUid(socialWeiboUser.getUid());
            entity.setExpiresIn(socialWeiboUser.getExpires_in());
            entity.setAccessToken(socialWeiboUser.getAccess_token());
            //查询社交用户账号信息
            try {
                HashMap<String, String> headers = new HashMap<>();
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token",socialWeiboUser.getAccess_token());
                map.put("uid",socialWeiboUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", headers, map);
                if(response.getStatusLine().getStatusCode() == 200){
                    String result = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(result);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    entity.setNickname(name);
                    entity.setGender("m".equalsIgnoreCase(gender)?1:0);
                }
            }catch (Exception e){
                log.error("查询社交信息失败",e);
            }
            this.baseMapper.insert(entity);
        }
        return entity;
    }

}